/*
 * StringDocument.java
 *
 * Created on 28 March 2007, 20:33
 *
 */

package rxtokenizer;

import java.io.*;

/**
 *
 * @author Ruslan Fayzrakhmanov
 */
public class StringDocument implements IDocument {
    
    static final int readBufferSize = 10240;
    
    public StringDocument() {
        content = new String();
    }
    
    public StringDocument(String content) {
        this.content = content;
    }

    public StringDocument(File file) throws FileNotFoundException, IOException {
        Reader rin = null;
        rin = new BufferedReader( new InputStreamReader(new FileInputStream(file)) );
        init(rin);
        rin.close();
    }
    
    public StringDocument(File file, String charsetName) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        Reader rin = null;
        rin = new BufferedReader( new InputStreamReader(new FileInputStream(file), charsetName) );
        init(rin);
        rin.close();
    }
    
    public StringDocument(InputStream in) throws IOException {
        Reader rin = null;
        rin = new BufferedReader(new InputStreamReader(in));
        init(rin);
    }
    
    private void init(Reader in) throws IOException {
        StringBuffer sb = new StringBuffer();
        char[] buffer = new char[readBufferSize];
        int len;
        while (( len = in.read(buffer) )>0) {
            sb.append(buffer, 0, len);
        }
        content = sb.toString();
    }
    
    public String getText() {
        return content;
    }
    
    public String getText(Region region) {
        return content.substring(region.getStart(), region.getEnd());
    }
    
    public Region toRegion() {
        return new Region(0, content.length(), this);
    }
    
    public String toString() {
        return content;
    }
    
    private String content;
    
}
